<?php

/**
 * Vega Framework
 *
 * @url http://vega.com.vn
 * @url http://clip.vn
 */

class Vega_Log 
{
	const ERROR			= 0;			// Error conditions
	const WARNING		= 1;			// Warning conditions
	const DEBUG			= 2;			// Debug-level messages
	
	protected 
		$_message		= null,	
		$_app			= null,		
		$_extras		= null,			// Extra log event
		$_level 		= 2,
		$_writer		= array(),
		$_levels		= array(
			self::ERROR		=> 'ERROR',
			self::WARNING 	=> 'WARNING',
			self::DEBUG		=> 'DEBUG'
		);
	
	protected static $_logger;
	
	public function __construct(Vega_Log_Writer $writer = null)
	{
		if ($writer != null)
		{
			$this->addWriter($writer);
		}
		else
		{
			require_once 'Vega/Log/Writer.php';
			
    		$config = Vega_App::getInstance()->coreConfig;
			
			$writer = new Vega_Log_Writer($config['logging']['dir'].DS.$config['logging']['files']['error']);
			
			$this->setApp(Vega_App::getInstance()->getAppName());
			
			$this->addWriter($writer);
		}
	}
		
	public static function getInstance()
	{
		if (!isset(self::$_logger))
		{
			$class	= __CLASS__;
			self::$_logger = new $class();
		}
		
		return self::$_logger;
	}
	
	public function log($message, $level = self::DEBUG)
	{	
		// write to log if config level is higher
		if ($this->_level >= $level)
		{
			$logEntry	= array_merge(array(
										'timestamp'		=> date('d-m-Y H:m:s'),
										'app'			=> $this->_app,
										'level'			=> $this->_levels[$level],
										'message'		=> $message,
										'extras'		=> $this->_extras));
			
			foreach($this->_writer AS $writer)
			{
				$writer->write($logEntry);
			}	
		}
	}
	
	public function debug($message)
	{
		return $this->log($message, self::DEBUG);
	}
	
	public function warning($message)
	{
		return $this->log($message, self::WARNING);
	}
	
	public function error($message)
	{
		return $this->log($message, self::ERROR);
	}
	
	public function getLevel()
	{
		return $this->_level;
	}
	
	public function setLevel($level)
	{
		$this->_level = $level;
	}
	
	public function setApp($app)
	{
		$this->_app	= $app;
	}

    public function setWriter(Vega_Log_Writer $writer)
    {
        $this->_writer = null;

        $this->_writer[] = $writer;
    }
	
	public function addWriter(Vega_Log_Writer $writer)
	{
		$this->_writer[] = $writer;
	}
	
	public function addExtras( $value )
	{
		$this->_extras = (string)$value;
	}	
}